<template>
  <view class="page">
    <view class="box flex">
      <view class="zt">活动主题</view>
      <image :src="img" mode="scaleToFill" />
      <view class="tip">本次活动二维码扫码可进入小程序查看活动</view>
    </view>
    <view class="bottom">
      <view class="btn" @click="handleSave">保存至手机相册</view>
    </view>
  </view>
</template>
<script>
import { getQRCode } from "@/utils/request.js";
export default {
  data() {
    return {
      id: "",
      img: "",
      filePath:''
    };
  },
  onLoad(option) {
    this.id = option.id;
    this.getCode();
  },
  methods: {
    async getQRCode(data) {
      return await getQRCode(data);
    },
   saveArrayBufferToFile(img) {
      let base64 = img.replace(/^data:image\/\w+;base64,/, "");
      var number = Math.random();
      let filePath = wx.env.USER_DATA_PATH + "/qrImg" + number + ".png";
      uni.getFileSystemManager().writeFile({
        filePath: filePath, //创建一个临时文件名
        data: base64, //写入的文本或二进制数据
        encoding: "base64", //写入当前文件的字符编码
        success: (res) => {
          this.filePath=filePath
        }
      })
    },
    handleSave() {
      let base64 = this.img.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
      var number = Math.random();
      let filePath = wx.env.USER_DATA_PATH + "/qrImg" + number + ".png";
      uni.getFileSystemManager().writeFile({
        filePath: filePath, //创建一个临时文件名
        data: base64, //写入的文本或二进制数据
        encoding: "base64", //写入当前文件的字符编码
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: filePath,
            success: function (res2) {
              uni.showToast({
                title: "保存成功！",
                icon: "none",
                duration: 5000,
              });
            },
            fail: function (err) {
              // console.log(err.errMsg);
            },
          });
        },
        fail: (err) => {
          //console.log(err)
        },
      });
    },
    getCode() {
      const data = {
        activity_id: this.id,
        page: "pagesB/release/activeDetail",
      };
      this.getQRCode(data).then((res) => {
        if (res) {
          this.img = res.base64;
          this.saveArrayBufferToFile(res.base64);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.page {
  padding-top: 28rpx;

  .box {
    width: 694rpx;
    height: 545rpx;
    background: #ffffff;
    border-radius: 15rpx;
    margin: 0 auto;
    flex-direction: column;
    justify-content: center;
    padding-bottom: 34rpx;

    .zt {
      font-size: 23rpx;
      padding-top: 84rpx;
    }

    image {
      width: 200rpx;
      height: 200rpx;
      margin-top: 61rpx;
    }

    .tip {
      font-size: 25rpx;
      text-align: center;
      width: 300rpx;
      margin-top: 51rpx;
    }
  }

  .bottom {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    padding-bottom: 40rpx;
  }
}
</style>